<template>
    <div>
        <el-upload class="avatar-uploader" :action="action" :headers="headers" :on-success="handleSuccess"
                   :before-upload="beforeUpload" :show-file-list="false">
            <!--<img v-if="editForm.picture != ''" :src="editForm.picture" class="avatar">-->
            <i v-if="!value" class="el-icon-plus avatar-uploader-icon"/>
            <slot name="preview"></slot>
        </el-upload>
    </div>
</template>

<script>
    import {getToken} from '@/utils/auth'

    export default {
        name: "UploadFile",
        props: {
            value: String,
            action: {
                type: String,
                default: process.env.VUE_APP_BASE_API + '/admin/component/oss/upload'
            }
        },
        data() {
            return {
                headers: {
                    token: ''
                },
            }
        },
        model: {
            prop: 'value',
            event: 'change'
        },
        methods: {
            beforeUpload(file) {
                console.log(arguments)
                this.headers.token = getToken();
                //声音格式要考虑h5的播放能力
                let isType = /^image\/(jpeg|png|bmp)$/i.test(file.type)
                    || /^audio\/(mp3|mpeg|wav|pcm|ogg)$/i.test(file.type)
                    || /^video\/(mp4|avi|ogg)$/i.test(file.type);
                let isSize = file.size / 1024 / 1024 < 8;

                if (!isType) {
                    this.$message.error('不支持的图片、声音、视频格式!');
                }
                if (!isSize) {
                    this.$message.error('上传文件大小不能超过 8MB!');
                }
                return isType && isSize;
            },
            handleSuccess(res, file) {
                console.log(arguments)
                this.value = res.data.urls;
                this.$emit('change', res.data.urls)
            },
        }
    }
</script>

<style scoped>
</style>
